package edu.tsinghua.eea.powermanagement.adapters;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import com.sun.crypto.provider.RSACipher;

import edu.tsinghua.eea.powermanagement.data.AppInfoCell;
import edu.tsinghua.eea.powermanagementserver.model.DBConnection;
import edu.tsinghua.eea.powermanagementserver.model.PMLog;

public class DBAppAdapter {
	public static void add(DBConnection dbc, int typeID, String name, int homeID){
		dbc.update("INSERT INTO appliance_info(ETypeID,Name,HomeID) VALUES('" + typeID 
				+ "','" + name + "','" + homeID + "');");
	}
	
	public static boolean exists(DBConnection dbc, int id){
		ResultSet rs = dbc.query("SELECT * FROM powermanagement.appliance_info a " +
				"WHERE a.`ID`='" + id + "';");
		boolean b = false;
		try{
			b = rs.next();
			rs.close();
		} catch (SQLException e){
			e.printStackTrace();
		}
		return b;
	}
	
	public static Vector<AppInfoCell> getApps(DBConnection dbc, int uid){
		ResultSet rs = dbc.query("SELECT a.`ID`,a.`Name` FROM appliance_info a " +
				"WHERE a.`HomeID`='" + uid + "';");
		Vector<AppInfoCell> va = new Vector<AppInfoCell>();
		try{
			while(rs.next()){
				AppInfoCell a = new AppInfoCell();
				a.mID = rs.getInt(1);
				a.mName = rs.getString(2);
				va.add(a);
			}
		} catch(SQLException e){
			e.printStackTrace();
		}
		
		return va;
	}
	
	public static boolean checkUserApp(DBConnection dbc, int appid, int uid){
		boolean b = false;
		ResultSet rs = dbc.query("SELECT * FROM powermanagement.appliance_info p " +
				"WHERE p.`ID`='" + appid + "' AND p.`HomeID`='" + uid + "';");
		try{
			rs.next();
			b = true;
		} catch(SQLException e){
		}
		return b;
	}
	
	public static void delete(DBConnection dbc, int appid){
		System.out.println("DELETE FROM appliance_info " +
				"WHERE `ID`='" + appid + "';");
		dbc.update("DELETE FROM appliance_info " +
				"WHERE `ID`='" + appid + "';");
	}
}
